import-module RSDD -Force

if (test-path variable:\psise)
{
throw 'Invoke-RSDDThreaded.psl must be run from powershell.exe and NOT powershell_ise.exe!'
break
)

#Script adapted from threading code by Osin Grehan
#http://www.nivot.org/2009/01/22/CTP3TheRunspaceFactoryAndPowerShellAccelerators.aspx

# create a pool of runspaces
$pool = [runspacefactory]::CreateRunspacePool(1, $MaxRunspaces)
$pool.Open()

Write-Verbose "Available Runspaces: $($pool.GetAvailableRunspaces())" 
$jobs = @()  
$ps = @()  
$wait = @()   

$connStrings = Get-ConnectionString
for ($i = 0; $i -lt $connStrings.Count; $i++)
{
    # create a "powershell pipeline runner"
    $ps += [powershell]::create()

    # assign our pool of runspaces to use
    $ps[$i].runspacepool = $pool

    [string]$connectionString = $connStrings[$i].ConnectionString
    [string]$dbmsType = $connStrings[$i].dbmsType
    [string]$name = $connStrings[$i].Name

    Write-Verbose "Import-RSDD $Name $dbmsType"

    # Assign Scripts to powershell object
    [void]$ps[$i].AddScript("Import-Module RSDD -ArgumentList 1; Import-RSDD -ConnectionString '$connectionString' -dbmsType '$dbmsType' -ConnectionName '$name'")
    
    # start job  
    $jobs += $ps[$i].BeginInvoke();  
      
    write-Verbose "Available runspaces: $($pool.GetAvailableRunspaces())" 
      
    # store wait handles for WaitForAll call  
    $wait += $jobs[$i].AsyncWaitHandle   

}

 # wait 1 hour for all jobs to complete, else abort  
 $success = [System.Threading.WaitHandle]::WaitAll($wait, 3600000)  
  
 Write-Verbose "All completed? $success" 
  
 # end async call  
 for ($i = 0; $i -lt $connStrings.Count; $i++) {  
  
     Write-Verbose "Completing async pipeline job $i" 
  
     try {  
         # complete async job  
         $ps[$i].EndInvoke($jobs[$i])  
     } catch {  
         # oops-ee!  
         Write-Warning "error: $_" 
     }  
  
     # dump info about completed pipelines  
     $info = $ps[$i].InvocationStateInfo  
  
     Write-Verbose "State: $($info.state) ; Reason: $($info.reason)" 
 }  
  
 Write-Verbose "Available runspaces: $($pool.GetAvailableRunspaces())"  
